<template>
  <el-upload
    ref="deleteImg"
    :class="{ disabled: isHidden }"
    v-model="fileList"
    list-type="picture-card"
    :auto-upload="false"
    :on-change="changeImg"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :http-request="getImgUrl"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script>
import { Plus } from "@element-plus/icons-vue";
export default {
  emits: ["getImgUrl"],
  data: () => {
    return {
      //用于判断是否只有一张图片
      imgArr: [],
      //是否继续添加上传框
      isHidden: false,
      //存放图片的路径
      fileList: [],
      //预览图片的路径
      dialogImageUrl: "",
      //是否显示弹窗
      dialogVisible: false,
    };
  },
  watch: {
    imgArr: {
      handler(newValue) {
        if (newValue.length == 1) {
          this.isHidden = true;
        } else {
          this.isHidden = false;
        }
      },
      immediate: true,
    },
  },
  methods: {
    //限定只能有一张图片
    changeImg(uploadFile, uploadFiles) {
      this.imgArr = uploadFiles;
      this.fileList.push(uploadFile);
    },
    //删除图片
    handleRemove(uploadFile, uploadFiles) {
      this.isHidden = false;
    },
    //预览图片
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url;
      this.dialogVisible = true;
    },
    //把图片抛出去
    async getImgUrl(option) {
      const result = await getUserUploadAPI(option);
      console.log(">>>>", result);
      this.fileList = result;
      this.$emit("getImgUrl", result);
    },
  },
};
</script>
<style>
.disabled .el-upload--picture-card {
  display: none;
}
.abled .el-upload--picture-card {
  display: block;
}
</style>
